﻿using System.IO;
using LitJson;
using UnityEngine;
using System;

namespace Shipwar.SDK
{
    public class FakeSDK : SDK
    {
        string usernamePath
        {
            get
            {
                return Application.persistentDataPath + "/username";
            }
        }

        public override void StartLogin()
        {
            FileInfo info = new FileInfo(usernamePath);
            if (!info.Exists)
            {
                System.DateTime currentTimestamp = System.DateTime.Now;
                System.DateTime beginTimestamp = new System.DateTime(1970, 1, 1, 0, 0, 0);
                long timestamp = (long)(currentTimestamp - beginTimestamp).TotalSeconds;
                JsonData newUser = new JsonData();
                newUser["AppUID"] = Guid.NewGuid().ToString();
                newUser["APPToken"] = currentTimestamp.ToString();
                newUser["Name"] = "";
                StreamWriter sw = info.CreateText();
                sw.WriteLine(newUser.ToJson());
                sw.Close();
                sw.Dispose();
                Debug.Log("New Player");
            }

            StreamReader sr = File.OpenText(usernamePath);
            string fileText = sr.ReadToEnd();
            JsonData usernameJson = JsonMapper.ToObject(fileText);

            User oldUser = new User();
            oldUser.APPToken = (string)usernameJson["APPToken"];
            oldUser.AppUID = (string)usernameJson["AppUID"];
            oldUser.Name = (string)usernameJson["Name"];
            oldUser.LoginType = 0;

            currentUser = oldUser;

            FireOnLogin();
        }

        public override void QuitLogin()
        {
            FileInfo info = new FileInfo(usernamePath);
            if (info.Exists)
            {
                File.Delete(usernamePath);
            }
        }
    }
}
